package com.da.javatest.thread.juc.semaphore;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author chenlida
 * @date 2020/7/11 22:44
 *
 * 程序中增加了一个变量 acquireSuccess用来标记获取许可是否成功，在finally中根据这个变量是否为true，来确定是否释放许可。
 */
public class Semaphore3 {
    private static Semaphore semaphore = new Semaphore(1);

    public static class MyThread extends Thread {
        public MyThread(String name) {
            super(name);
        }

        @Override
        public void run() {
            Thread thread = Thread.currentThread();
            //获取许可是否成功
            boolean acquireSuccess = false;
            try {
                semaphore.acquire();
                acquireSuccess = true;
                System.out.println(thread.getName() + "获得许可,当前可用许可为:" + semaphore.availablePermits());
                TimeUnit.SECONDS.sleep(5);
                System.out.println(thread.getName() + "运行结束");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                if (acquireSuccess) {
                    semaphore.release();
                }
            }
            System.out.println(thread.getName() + "当前可用许可为:" + semaphore.availablePermits());
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyThread t1 = new MyThread("t1");
        t1.start();
        TimeUnit.SECONDS.sleep(1);
        MyThread t2 = new MyThread("t2");
        t2.start();
        TimeUnit.SECONDS.sleep(1);
        MyThread t3 = new MyThread("t3");
        t3.start();

        // t2,t3发出中断
        t2.interrupt();
        t3.interrupt();
    }
}
